<template>
  <a-modal
    title="编辑报工表"
    width="80%"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item v-show="false"><a-input v-decorator="['id']" /></a-form-item>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              label="工单编号"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="(input, option) =>{
                  return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )
                }"
                @change="workOrderIdChange"
                allowClear
                style="width: 100%"
                placeholder="请选择工单编号"
                v-decorator="['workOrderId', {rules: [{ required: true, message: '请选择工单！' }]}]">
                <a-select-option
                  v-for="(item,index) in list.workOrder"
                  :key="index"
                  :value="item.id"
                  :disabled="item.status !== 0">{{ item.workOrderNo }}
                  {{ item.proName }}
                  <a-statistic v-if="item.status === -1" :value-style="{fontSize:'15px' }" value="状态 : 未开始"/>
                  <a-statistic
                    v-if="item.status === 0"
                    :value-style="{fontSize:'15px',color : '#3f8600' }"
                    value="状态 : 执行中"/>
                  <a-statistic
                    v-if="item.status === 1"
                    :value-style="{ fontSize:'15px',color : '#cf1322'}"
                    value="状态 : 已结束"/>
                  <a-statistic
                    v-if="item.status === -2"
                    :value-style="{fontSize:'15px', color : '#800080'}"
                    value="状态 : 已取消"/>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId')">
            <a-form-item
              label="任务工序"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-select
                show-search
                option-filter-prop="children"
                :filter-option="(input, option) =>{
                  return (
                    option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  )
                }"
                @change="taskIdChange"
                style="width: 100%"
                placeholder="请选择任务工序"
                v-decorator="['taskId', {rules: [{ required: true, message: '请选择任务工序！' }]}]">
                <a-select-option
                  v-for="(item,index) in list.task"
                  :key="index"
                  :value="item.id"
                  :disabled="item.status !== 0"
                >
                  <a-popover placement="left">
                    <span role="img" :aria-label="item.workStepName">
                      <a-tag v-if="item.workStepName">{{ item.workStepName }}</a-tag>
                      <a-tag v-if="item.sortNum" color="green">顺序 : {{ item.sortNum }}</a-tag>
                    </span>
                    <template slot="content" v-if="hasPerm('task:edit')& editEnable" >
                      <a-radio-group placeholder="请选择任务状态" v-model="item.status" @change="selectStatus(item)">
                        <a-radio :value="-1" >未开始</a-radio>
                        <a-radio :value="0" >执行中</a-radio>
                        <a-radio :value="1" :disabled="item.status === -1">已结束</a-radio>
                      </a-radio-group>
                    </template>
                  </a-popover>
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="生产人员"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <user-select
                placeholder="请选择生产人员"
                v-decorator="['productionUser', { rules: [{ required: true, message: '请选择生产人员！' }]}]"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="报工数量"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input-number
                :min="0"
                v-decorator="['reportNum', {rules: [{ required: false, message: '请输入报工数量！' }]}]"
                @change="(val)=>{
                  form.setFieldsValue({
                    goodNum: val - form.getFieldValue('badNum'),
                    badNum: form.getFieldValue('reportNum') - form.getFieldValue('goodNum')
                  })
                }"
                style="width: 100%"
                placeholder="请输入报工数量"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="良品数量"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input-number
                @change="(val)=>{
                  form.setFieldsValue({
                    badNum: form.getFieldValue('reportNum') - val
                  })
                }"
                v-decorator="['goodNum', {rules: [{ required: false, message: '请输入良品数量！' }]}]"
                style="width: 100%"
                placeholder="请输入良品数量"
              />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="不良品数"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-input-number
                @change="(val)=>{
                  form.setFieldsValue({
                    reportNum: form.getFieldValue('goodNum') + val
                  })
                }"
                style="width: 100%"
                placeholder="请输入不良品数"
                v-decorator="['badNum', {rules: [{ required: false, message: '请输入良品数量！' }]}]" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item
              label="工作时间"
              :labelCol="labelCol_T"
              :wrapperCol="wrapperCol_T"
              has-feedback
            >
              <a-range-picker
                style="width: 100%"
                :ranges="{ '当天': [moment('08:30', 'HH:mm'), moment('17:30', 'HH:mm')] }"
                format="YYYY-MM-DD HH:mm"
                :placeholder="['开始时间', '结束时间']"
                v-decorator="['startEndTime', {rules: [{ required: true, message: '请输入工作时间！' }]}, ] "
                @change="workTimeChange" />
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24" v-show="form.getFieldValue('workOrderId') && form.getFieldValue('taskId')">
            <a-form-item label="工作时长" :labelCol="labelCol_T" :wrapperCol="wrapperCol_T">
              <a-form-item
                style="display: inline-flex"
              ><a-input
                style="width: 80%"
                type="number"
                v-decorator="['workHour', { initialValue: 9 }]"
                @change="workHourChange"
                oninput="if(value<0)value=0;if(value>8640)value=8640"
              /><span style="padding-left: 2%">小时</span></a-form-item
              >
              <a-form-item
                style="display: inline-flex"
              ><a-input
                style="width: 80%"
                type="number"
                v-decorator="['workMoment', { initialValue: 0 }]"
                @change="workMomentChange"
                oninput="if(value<0)value=0;if(value>59)value=59"
              /><span style="padding-left: 2%">分钟</span></a-form-item
              >
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item
          label="备注信息"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          has-feedback
        >
          <a-textarea placeholder="请输入备注" v-decorator="['remarks']" :auto-size="{ minRows: 3, maxRows: 6 }"/>
        </a-form-item>
      </a-form>
      <a-row :gutter="24" style="margin: 60px;">
        <a-col :md="4" :sm="24" v-show="curTask">
          <a-statistic v-if="curTask.status === -1" title="工序状态" value="未开始"/>
          <a-statistic v-if="curTask.status === 0" title="工序状态" :value-style="{ color : '#3f8600'}" value="执行中"/>
          <a-statistic v-if="curTask.status === 1" title="工序状态" :value-style="{ color : '#cf1322'}" value="已结束"/>
        </a-col>
        <a-col :md="6" :sm="24" v-show="!$utils.isEmpty(curTask) && !$utils.isUndefined(curTask.plaNum) && !$utils.isUndefined(curTask.goodNum)">
          <a-statistic
            :value-style="{ color: curTask.goodNum - recordGoodNum + form.getFieldValue('goodNum') < curTask.plaNum ? '#3f8600' : '#cf1322'}"
            title="工序进度"
            :value="curTask.goodNum - recordGoodNum + '+' + form.getFieldValue('goodNum')">
            <template #suffix>
              <span> / {{ curTask.plaNum }}</span>
            </template>
          </a-statistic>
        </a-col>

      </a-row>

    </a-spin>
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import { workReportEdit } from '@/api/modular/main/workreport/workReportManage'
  import { workOrderList } from '@/api/modular/main/workorder/workOrderManage'
  import { taskEdit, taskList } from '@/api/modular/main/task/taskManage'
  import XEUtils from 'xe-utils'
  import UserSelect from '@/components/MyComp/UserSelect'
  export default {
    components: {
      UserSelect
    },
    props: {
      editEnable: {
        type: Boolean,
        default: true,
        required: false
      }
    },
    data () {
      return {
        recordGoodNum: 0,
        curTask: '',
        list: {
          workOrder: [],
          task: []
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 3 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        },

        labelCol_T: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol_T: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        startEndTimeString: '',
        startEndTimeArray: [],
        endTimePicker: [],
        visible: false,
        confirmLoading: false,
        form: this.$form.createForm(this)
      }
    },
    methods: {
      selectStatus(values) {
        taskEdit(values).then((res) => {
          if (res.success) {
            this.$message.success('状态修改成功')
            this.confirmLoading = false
            this.$emit('ok', values)
          } else {
            this.$message.error(res.message)
          }
        }).finally((res) => {
          this.confirmLoading = false
        })
      },
      moment,
      workOrderIdChange(val) {
        this.form.setFieldsValue({
          taskId: null
        })
        this.curTask = ''
        taskList({ workOrderId: val }).then(res => {
          this.list.task = res.data
        })
      },
      taskIdChange(val) {
        this.curTask = XEUtils.find(this.list.task, item => item.id === val)
      },
      // 初始化方法
      edit (record) {
        this.visible = true
        workOrderList().then(res => {
          // 工单列表初始化
          this.list.workOrder = res.data
        })
        this.mulBadItemData = this.$options.filters['dictData']('bad_item')

        taskList({ workOrderId: record.workOrderId }).then(res => {
          // 表单任务
          this.list.task = res.data
          // 当前任务赋值
          this.curTask = XEUtils.find(this.list.task, item => item.id === record.taskId)
        })

        // 良品数量
        this.recordGoodNum = record.goodNum

        // 表单赋值
        this.$nextTick(() => {
          this.form.setFieldsValue({
            id: record.id,
            workOrderId: record.workOrderId,
            taskId: record.taskId,
            mulBadItem: record.mulBadItem ? record.mulBadItem.split(';') : [],
            productionUser: record.productionUser,
            reportNum: record.reportNum || 0,
            goodNum: record.goodNum || 0,
            badNum: record.badNum || 0,
            workHour: Math.floor(record.workTime / 60) || 0,
            workMoment: record.workTime % 60 || 0,
            remarks: record.remarks
          })
          // 时间单独处理
          if (record.startTime && record.endTime) {
            this.form.getFieldDecorator('startEndTime', { initialValue: [moment(record.startTime, 'YYYY-MM-DD HH:mm'), moment(record.endTime, 'YYYY-MM-DD HH:mm')] })
            this.startEndTimeString = [moment(record.startTime).format('YYYY-MM-DD HH:mm'), moment(record.endTime).format('YYYY-MM-DD HH:mm')].join(';')
            this.startEndTimeArray = this.startEndTimeString.split(';')
            this.endTimePicker = moment(this.startEndTimeArray[1]).subtract(this.form.getFieldValue('workMoment'), 'minutes')
            this.endTimePicker = moment(this.endTimePicker).format('YYYY-MM-DD HH:mm')
          }
        })
      },
      // 修改时间选择器
      workTimeChange(date, dateStrArr) {
        this.$nextTick(() => {
          this.form.setFieldsValue({
            workHour: Math.floor(moment(dateStrArr[1]).diff(dateStrArr[0]) / (1000 * 60) / 60),
            workMoment: (moment(dateStrArr[1]).diff(dateStrArr[0]) / (1000 * 60)) % 60
          })
          this.startEndTimeString = dateStrArr.join(';')
          this.startEndTimeArray = dateStrArr
        })
      },
      // 修改工作时长——时
      workHourChange() {
        this.$nextTick(() => {
          this.startEndTimeArray[0] = moment(this.startEndTimeArray[0], 'YYYY-MM-DD HH:mm:ss')
          this.startEndTimeArray[1] = moment(this.startEndTimeArray[0]).add(this.form.getFieldValue('workHour'), 'hours')
          this.startEndTimeArray[1] = moment(this.startEndTimeArray[1]).add(this.form.getFieldValue('workMoment'), 'minutes')
          this.endTimePicker = moment(this.startEndTimeArray[1]).subtract(this.form.getFieldValue('workMoment'), 'minutes')
          this.form.setFieldsValue({
            startEndTime: this.startEndTimeArray
          })
          this.startEndTimeString = [
            moment(this.startEndTimeArray[0]).format('YYYY-MM-DD HH:mm'),
            moment(this.startEndTimeArray[1]).format('YYYY-MM-DD HH:mm')
          ].join(';')
        })
      },
      // 修改工作时长——分
      workMomentChange() {
        this.$nextTick(() => {
          this.startEndTimeArray = this.startEndTimeString.split(';')
          this.startEndTimeArray[0] = moment(this.startEndTimeArray[0], 'YYYY-MM-DD HH:mm:ss')
          this.startEndTimeArray[1] = moment(this.endTimePicker).add(this.form.getFieldValue('workMoment'), 'minutes')
          this.form.setFieldsValue({
            startEndTime: this.startEndTimeArray
          })
          this.startEndTimeString = [
            moment(this.startEndTimeArray[0]).format('YYYY-MM-DD HH:mm'),
            moment(this.startEndTimeArray[1]).format('YYYY-MM-DD HH:mm')
          ].join(';')
        })
      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            if (values.mulBadItem) {
              values.mulBadItem = values.mulBadItem.join(';')
            }
            for (const key in values) {
              if (typeof (values[key]) === 'object' && values[key] != null) {
                values[key] = JSON.stringify(values[key])
              }
            }
            values.startEndTime = this.startEndTimeString || null
            values.workTime = values.workHour * 60 + parseInt(values.workMoment)
            workReportEdit(values).then((res) => {
              if (res.success) {
                this.$message.success('编辑成功')
                this.confirmLoading = false
                this.$emit('ok', values)
                this.handleCancel()
              } else {
                this.$message.error(res.message)
              }
            }).finally((res) => {
              this.confirmLoading = false
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      handleCancel () {
        this.curTask = {}
        this.startEndTimeString = ''
        this.form.getFieldDecorator('startEndTime', { initialValue: null })
        this.form.resetFields()
        this.visible = false
      }
    }
  }
</script>
